import tkinter as tk
import keyboard, pyautogui
from threading import Timer
import random

class BindKeyboardEventsController:
  def __init__(self, tk_root) -> None:
    self.tk_root = tk_root
    self.build_ui()
    self.mouse_interval_click_timer = None

  def build_ui(self):
    tk.Button(self.tk_root, text="启动按键监听", command=self.bind_keyboard_events).place(x=10, y=50, width=80, height=30)
    tk.Button(self.tk_root, text="停止按键监听", command=self.unbind).place(x=100, y=50, width=80, height=30)

  def on_key_event(self, event):
    if event.event_type == keyboard.KEY_DOWN:
      if event.name == 'f7':
        print("f7键被按下，执行另一个动作")
        self.start_mouse_interval_click()
      elif event.name == 'f8':
        self.stop_all_actions()
        print("f8键被按下，执行另一个动作")
      else:
        pass
        # print(f"按键 {event.name} 被按下")

  def start_mouse_interval_click(self):
    self.stop_mouse_interval_click()
    x, y = pyautogui.position()
    pyautogui.click(x, y)
    # print("鼠标点击")
    self.mouse_interval_click_timer = Timer(0.1, self.start_mouse_interval_click)
    self.mouse_interval_click_timer.start()
    # 开启鼠标连点
  
  def stop_mouse_interval_click(self):
    if self.mouse_interval_click_timer:
      self.mouse_interval_click_timer.cancel()
      self.mouse_interval_click_timer = None

  def stop_all_actions(self):
    self.stop_mouse_interval_click()

  def bind_keyboard_events(self):
    print("开始监听")
    # 开始监听
    keyboard.hook(self.on_key_event)

  def unbind(self):
    # 停止监听
    print("停止监听")
    keyboard.unhook_all()